<template>
  <xn-dialog custom-class="edit-user-dialog" :title="title" :visible.sync="selfVisible" @close="onDialogHide">
    <div class="content">
      <el-form ref="form" :model="form" label-width="100px" label-suffix="：" :rules="rules">
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入姓名" :maxlength="10" clearable></el-input>
        </el-form-item>
        <el-form-item label="职位" prop="post">
          <el-input v-model="form.post" placeholder="请输入职位信息" :maxlength="30" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入工作邮箱" :maxlength="30" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入11位手机号" :maxlength="11" clearable></el-input>
        </el-form-item>
        <el-form-item v-if="showSmsSend" label="验证码" prop="smsCode">
          <el-input v-model="form.smsCode" placeholder="请输入验证码" :maxlength="6" clearable>
            <el-button
              slot="append"
              class="send-btn"
              :class="{ disabled: sendCodeStatus === 'send' }"
              @click="sendCode(1)">
              {{ codeBtnDisplay }}
            </el-button>
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <div class="footer" slot="footer">
      <el-button type="default" @click="selfVisible = false">取消</el-button>
      <el-button type="primary" @click="onSubmit">确定</el-button>
    </div>
  </xn-dialog>
</template>
<script>
import { getIdentifyingCode, addUserBook, editUserBook } from '@api/modules/user.js'

import XnDialog from '@com/xnDialog.vue'
import { phoneReg, checkCodeReg, emailReg } from '@utility/regExps.js'

export default {
  name: 'EditUserDialog',
  components: {
    XnDialog,
  },
  props: {
    visible: {
      type: Boolean,
    },
    editInfo: {
      type: Object,
    },
  },
  data() {
    return {
      cutdownSec: 0,
      selfVisible: false,
      sendCodeStatus: 'init', // init, send, retry
      form: {
        userName: '',
        post: '',
        email: '',
        phone: '',
        smsCode: '',
      },
      rules: {
        userName: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur',
          },
        ],
        post: [
          {
            required: true,
            message: '请输入职位信息',
            trigger: 'blur',
          },
        ],
        phone: [
          {
            required: true,
            message: '请输入有效的手机号',
            trigger: 'blur',
            pattern: phoneReg,
          },
        ],
        smsCode: [
          {
            required: true,
            message: '请输入有效的验证码',
            trigger: 'blur',
            pattern: checkCodeReg,
          },
        ],
        email: [
          {
            required: false,
            message: '请输入有效的邮箱',
            trigger: 'blur',
            pattern: emailReg,
          },
        ],
      },
    }
  },
  computed: {
    title() {
      if (this.editInfo) {
        return '编辑用户'
      }
      return '新增用户'
    },
    codeBtnDisplay() {
      if (this.sendCodeStatus === 'init') {
        return '发送验证码'
      } else if (this.sendCodeStatus === 'send') {
        return this.cutdownSec + ' 秒'
      }
      return '重新发送'
    },
    showSmsSend() {
      if (this.editInfo && this.editInfo.phone === this.form.phone) {
        return false
      }
      return true
    },
  },
  watch: {
    visible(visible) {
      this.selfVisible = visible
      if (visible) {
        if (this.editInfo) {
          for (const key in this.form) {
            this.form[key] = this.editInfo[key]
          }
        } else {
          this.form = {
            userName: '',
            post: '',
            email: '',
            phone: '',
            smsCode: '',
          }
          this.$nextTick(() => {
            this.$refs.form && this.$refs.form.resetFields()
            console.log('this.$refs.form...', this.$refs.form)
          })
        }
      }
    },
  },
  created() {},
  mounted() {},
  methods: {
    onDialogHide() {
      this.$emit('update:visible', false)
      this.$emit('closed')
    },
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.editInfo) {
            const postData = { id: this.editInfo.id, ...this.form }
            editUserBook(postData).then(res => {
              if (res.code === 0) {
                this.$message.success('更新联络员信息成功！')
                this.$emit('edit-success', postData)
                this.selfVisible = false
              }
            })
          } else {
            addUserBook(this.form).then(res => {
              if (res.code === 0) {
                this.$message.success('新增联络员信息成功！')
                this.$emit('add-success')
                this.selfVisible = false
              }
            })
          }
        }
      })
    },
    sendCode() {
      if (this.sendCodeStatus === 'send') {
        return
      }
      this.$refs.form.validateField('phone', invalid => {
        if (!invalid) {
          getIdentifyingCode(this.form.phone).then(res => {
            if (res.code === 0) {
              this.startCutdown()
            }
          })
        }
      })
    },
    startCutdown() {
      this.clearCutdownTimer()
      this.sendCodeStatus = 'send'
      this.cutdownSec = 60
      this.cutdownTimer = setInterval(() => {
        this.cutdownSec--
        if (this.cutdownSec <= 0) {
          this.clearCutdownTimer()
          this.sendCodeStatus = 'retry'
        }
      }, 1000)
    },
    clearCutdownTimer() {
      if (this.cutdownTimer) {
        clearInterval(this.cutdownTimer)
        this.cutdownSec = 0
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.edit-user-dialog {
  ::v-deep &.el-dialog {
    height: 460px;
    width: 600px !important;
  }
  .content {
    height: 100%;
  }
}
</style>
